import { ref } from 'vue'

export function useChessSound() {
  const audioContext = ref<AudioContext | null>(null)
  
  const initAudio = () => {
    const initializeAudioContext = () => {
      if (!audioContext.value) {
        audioContext.value = new AudioContext()
      }
      document.removeEventListener('click', initializeAudioContext)
    }

    document.addEventListener('click', initializeAudioContext, { once: true })
  }

  const playMove = async () => {
    if (!audioContext.value) return
    const oscillator = audioContext.value.createOscillator()
    const gainNode = audioContext.value.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.value.destination)
    
    oscillator.frequency.value = 440
    gainNode.gain.value = 0.1
    
    oscillator.start()
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.value.currentTime + 0.1)
    oscillator.stop(audioContext.value.currentTime + 0.1)
  }

  const playCapture = async () => {
    if (!audioContext.value) return
    const oscillator = audioContext.value.createOscillator()
    const gainNode = audioContext.value.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.value.destination)
    
    oscillator.frequency.value = 220
    gainNode.gain.value = 0.2
    
    oscillator.start()
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.value.currentTime + 0.2)
    oscillator.stop(audioContext.value.currentTime + 0.2)
  }

  const playCheck = async () => {
    if (!audioContext.value) return
    const oscillator = audioContext.value.createOscillator()
    const gainNode = audioContext.value.createGain()
    
    oscillator.connect(gainNode)
    gainNode.connect(audioContext.value.destination)
    
    oscillator.frequency.value = 880
    gainNode.gain.value = 0.15
    
    oscillator.start()
    gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.value.currentTime + 0.15)
    oscillator.stop(audioContext.value.currentTime + 0.15)
  }

  return {
    initAudio,
    playMove,
    playCapture,
    playCheck
  }
} 